//
//  PayViewController.m
//  UESTCPioneer
//
//  Created by sss on 14-8-11.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PayViewController.h"
#import "CellForPay.h"
#import "CellForPay_input.h"
#import "MD5Hash.h"
#import "SVProgressHUD.h"
#import "YiJiPayPlugin.h"

#define kPartnerId  @"20140411020055684571"
#define kSignKey @"0b3ca56512f7dc39a63cadff06fa7892"
#define kUserId @"12345678"
#define kPayPath @"https://mpay.yijifu.net"
#define kYJmode      kYjModeTesting   //测试地址


@interface PayViewController ()<UITableViewDataSource,UITableViewDelegate,YiJiPayPluginDelegate>{
    NSArray *_leftLableArr;
    NSArray *_rightLableArr;
    NSString *_tradeNo;
    NSArray *_payList;
    BOOL _isPay;
    UIBarButtonItem *_button;
}

@end

@implementation PayViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    CGRect tabFrame = CGRectMake(0, 0, 320, 200);
    
    UITableView *myTab = [[UITableView alloc] initWithFrame:tabFrame style:UITableViewStyleGrouped];

    self.tableView = myTab;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[CellForPay class] forCellReuseIdentifier:@"payInfo"];
    [self.tableView registerClass:[CellForPay_input class] forCellReuseIdentifier:@"payInput"];
    _leftLableArr = @[@"姓       名",
                      @"学       院",
                      @"所属支部"];
    NSLog(@"%@",[constant getPersonalInfo]);
    NSLog(@"%@",[constant getBranch]);
    _rightLableArr = @[[[constant getPersonalInfo] objectForKey:@"name"],
                       [[constant getPersonalInfo] objectForKey:@"institute"],
                       [[constant getPersonalInfo] objectForKey:@"branch"]
                       ];
    _payList = @[@"2014年第四季度",
                 @"2014年第三季度",
                 @"2014年第二季度",
                 @"2014年第一季度"];
    _isPay = NO;
    
//    UIButton *checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 310, 120, 38)];
//    [checkBtn setTitle:@"立即缴费" forState:UIControlStateNormal];
//    [checkBtn.layer setCornerRadius:10.0];
//    [checkBtn.layer setBorderWidth:1];
//
//    checkBtn.backgroundColor = [UIColor redColor];
//    checkBtn.titleLabel.textColor = [UIColor whiteColor];
//    [checkBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:checkBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"isperson:%i",self.isPerson);
    if (self.isPerson) {
        self.navigationItem.title = @"党费缴纳";
        self.leveyTabBarController.navigationItem.title = @"";
    }
    else{
        NSLog(@"侧滑栏进入");
        self.navigationItem.title = @"";
        self.leveyTabBarController.navigationItem.title = @"党费缴纳";
        [self addLeftBtn];
    }

}
#pragma mark -
#pragma mark 侧滑按钮点击
-(void)addLeftBtn{
    if (_button == nil) {
        UIButton *leftMenu = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftMenu setImage:[UIImage imageNamed:@"menu.png"] forState:UIControlStateNormal];
        [leftMenu setImageEdgeInsets:UIEdgeInsetsMake(12, 12, 12, 42)];
        [leftMenu addTarget:self action:@selector(leftMenuClick) forControlEvents:UIControlEventTouchUpInside];
        _button = [helper BarButtonItemWithUIButton:leftMenu ButtonOrigin:CGPointMake(0, 0)];
    }
    
    [self.leveyTabBarController.navigationItem setLeftBarButtonItem:_button];
}

-(void)leftMenuClick{
    [self.leveyTabBarController.revealSideViewController pushOldViewControllerOnDirection:PPRevealSideDirectionLeft animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return _leftLableArr.count;
    else return _payList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"基本信息";
    }else{
        return @"缴费记录";
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CellForPay *cell = [tableView dequeueReusableCellWithIdentifier:@"payInfo" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[CellForPay alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"payInfo"];
        }
        cell.staticLabel.text = _leftLableArr[indexPath.row];
        cell.infoLabel.text = _rightLableArr[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        cell.userInteractionEnabled = NO;
        
        if (indexPath.row == 3) {
            UILabel *yuan = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width-5, cell.frame.size.height)];
            [yuan setTextAlignment:NSTextAlignmentRight];
            yuan.text = @"元";
            yuan.textColor = [UIColor colorWithRed:119.0/255.0 green:123.0/255.0 blue:134.0/255.0 alpha:1];
            [cell.contentView addSubview:yuan];
        }
        
        return cell;
    }else{
        CellForPay_input *cell = [tableView dequeueReusableCellWithIdentifier:@"payInput" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[CellForPay_input alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"payInput"];
        }

        cell.staticLabel.text = _payList[indexPath.row];
        cell.payNum.text = @"0.3元";
        
        if (indexPath.row>0) {
            UILabel *payLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width - 15, cell.frame.size.height)];
            payLable.textAlignment = NSTextAlignmentRight;
            payLable.textColor = [UIColor colorWithRed:194.0/255.0 green:58.0/255.0 blue:44.0/255.0 alpha:0.8];
            payLable.text = @"已支付";
            [cell.contentView addSubview:payLable];
        }
        else{
            UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(225, 10, 70, 24)];
            [payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
            payBtn.backgroundColor = [UIColor redColor];
            payBtn.titleLabel.textColor = [UIColor whiteColor];
            [payBtn.layer setCornerRadius:4.0];
            payBtn.layer.borderWidth = 0.1;
            payBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [payBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:payBtn];
        }
        return cell;
    }
}


#pragma mark -
#pragma mark 提交按钮点击
-(void)checkBtnClick{
    NSLog(@"点击提交");
//    [self getTradeNo];
    [self onStartSDK];
}

#pragma mark -
#pragma mark tap
-(void)tapAction{
    [self.view endEditing:YES];
}


#pragma mark -
#pragma mark 易极付相关函数
//1.获取交易号
-(void)getTradeNo{
    NSDictionary *param = @{@"service":@"createTradeOrder",@"partnerId":kPartnerId,@"partnerUserId":kUserId,@"orderNo":[self getSerialNumber],@"signType":@"MD5",@"sellerUserId":kPartnerId,@"tradeAmount":@"0.01",@"currency":@"CNY",@"tradeName":@"成电先锋党费缴纳",@"tradeMemo":@"党费缴纳" };
    NSMutableDictionary *param1 = [NSMutableDictionary dictionaryWithDictionary:param];
    
    NSString *sign = [self signParam: param];//调用自己写的签名函数对订单号请求参数进行签名
    [param1 setValue:sign forKey:@"sign"];
    [SVProgressHUD showWithStatus:@"正在创建交易号..."];

    [NetworkCenter requestCreateTransNo:param1 SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSLog(@"success");
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
    
    //20140812000014899671
}

-(NSString *)getSerialNumber
{
    NSString *serialNumber = [self getCurDateStringType:@"yyyyMMddHHmmss"];

    NSString *arc = [NSString stringWithFormat:@"%@",[kPartnerId substringToIndex:6]];
    serialNumber = [serialNumber stringByAppendingString:arc];
    return serialNumber;
}

-(NSString *)getCurDateStringType:(NSString *)type
{
    NSDate *now = [[NSDate alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:type];
    NSString *destDateString = [dateFormatter stringFromDate:now];
    
    return destDateString;
}
//2.获取本地唯一交易码
//3.MD5校验
-(NSString *)signParam:(NSDictionary *)bodyDic
{

    NSMutableArray *sortAy = [NSMutableArray array];
    
    for (NSString *key in bodyDic.allKeys) {
        NSDictionary *dic = @{key:[bodyDic objectForKey:key]};
        [sortAy addObject:dic];
    }
    
    NSArray *sortedArray = [sortAy sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDictionary *dic1 = (NSDictionary *)obj1;
        NSDictionary *dic2 = (NSDictionary *)obj2;
        return [[dic1.allKeys objectAtIndex:0] compare:[dic2.allKeys objectAtIndex:0]];
    }];//比较排序
    
    NSString *sign = @"";
    for (NSDictionary *dic in sortedArray) {
        for (NSString *key in dic.allKeys) {
            sign = [sign stringByAppendingFormat:@"%@=%@&",key,[dic objectForKey:key]];
        }
    }//将字典链接成请求链接的字符串
    
    sign = [sign substringToIndex:sign.length-1];
    sign = [sign stringByAppendingString:kSignKey];
    sign = [[MD5Hash md5:sign] lowercaseString];
    //NSLog(@"%@",sign);

    return sign;
}

//4.提交付款
-(void)onStartSDK
{

//    NSString *payNum = ((CellForPay_input*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]).textfield.text;
    
    NSDictionary *param = @{kYjParamMode:kYJmode,kYjParamPartnerID:kPartnerId,kYjParamSellerID:kPartnerId,kYjParamMemberID:kUserId,kYjParamOrderID:@"20140812000014899671",kYjParamSignKey:@"c9cef22553af973d4b04a012f9cb8ea8"};
    
    //    NSDictionary *param = @{kYjParamSellerID:_fieldParterID.text,kYjParamMemberID:kMerberID,kYjParamOrderID:_fieldTradeNo.text,kYjParamOutOrderID:OutOrderID};
    
    [YiJiPayPlugin startPay:param viewController:self delegate:self];
}

-(void)YiJiPayPluginResult:(NSDictionary *)result{
    NSLog(@"result:%@",result);
    [self alertShow:[result objectForKey:kYjResultMessage]];
    switch ([[result objectForKey:kYjResultStatus] integerValue]) {
        case 100:
            NSLog(@"支付成功");
            break;
        default:
            break;
    }
}

-(void)alertShow:(NSString*)showString{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:showString delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [alert show];
}
@end
